package com.learning.sims;

import android.os.Handler;
import android.util.Log;

import com.learning.sims.people.People;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by xie on 2017/4/22.
 *
 * 世界类相当于整个模拟人生游戏的时间轴，时间不停在走，且一直将当前时间通知给所有人
 *
 */

public class World {

    private List<People> mPeoples = new ArrayList<People>();
    private long mTimeRate = 10*60;
    private long mMinsTime;

    private Handler mHandler = new Handler();

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            mMinsTime += mTimeRate;
            notifyUpdateTime(mMinsTime);
            mHandler.postDelayed(this, 1000);
        }
    };

    public World() {
        start();
    }

    private void start(){
        mMinsTime = System.currentTimeMillis()/1000;
        mHandler.postDelayed(runnable, 1000);
    }

    public void stop(){
        mHandler.removeCallbacks(runnable);
    }

    public void addPeople(People people){
        if(!mPeoples.contains(people)){
            mPeoples.add(people);
        }
    }

    public void removePeople(People people){
        if(mPeoples.contains(people)){
            mPeoples.remove(people);
        }
    }

    private void notifyUpdateTime(long time){
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Log.d("Sims","time = "+sdr.format(new Date(time * 1000L)));
        for(People people:mPeoples){
            people.updateTime(time,this);
        }
    }

    public void setTimeSpeed(long rate){
        mTimeRate = rate;
    }

}
